import { AudioClip, AudioSource, resources } from "cc";
import { Epath } from "../../enum";





/** 声音管理 */
export class AudioManager {
    
    private _audioCaches: Record<string, AudioClip> = {};
    private _audioSource: AudioSource = null;
    

    init(audioSource: AudioSource) {
        this._audioSource = audioSource;

    }

    /** 播放音效 */
    playSound(name: string, volume: number = 1.0) {
        if (!this._audioSource) {
            console.warn('AudioSource is null');
            return;
        }

        let url = Epath.AUDIO_SOUND + name;
        if (this._audioCaches[url]) {
            this._audioSource?.playOneShot(this._audioCaches[url], volume);
        } else {
            resources.load(url, (err, audioClip) => {
                if (err) {
                    console.error("音效加载失败", err);
                    return;
                }
                this._audioCaches[url] = audioClip as AudioClip;
                this._audioSource?.playOneShot(this._audioCaches[url], volume);

            })
        }


    }

    /** 
     * 播放背景音乐
     * @param name 音乐资源名称
     * @param volume 音量 0-1
     * @param loop 是否循环播放 默认为true
     */
    playMusic(name: string, volume: number = 1.0, loop: boolean = true) {
        if (!this._audioSource) {
            console.warn('AudioSource is null');
            return;
        }
        let url = `${Epath.AUDIO_MUSIC}${name}`;
        if (this._audioCaches[url]) {
            this._audioSource.clip = this._audioCaches[url];
            this._audioSource.volume = volume;
            this._audioSource.loop = loop;
            this._audioSource.play();
        } else {
            resources.load(url, (err, audioClip) => {
                if (err) {
                    console.error("背景音乐加载失败", err);
                    return;
                }
                this._audioCaches[url] = audioClip as AudioClip;
                this._audioSource.clip = this._audioCaches[url];
                this._audioSource.volume = volume;
                this._audioSource.loop = loop;
                this._audioSource.play();
            })

        }
    }

}